package com.tmian.aiagent.Advisor;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ai.chat.client.advisor.api.*;
import org.springframework.ai.chat.model.MessageAggregator;
import reactor.core.publisher.Flux;

public class MyLoggerAdvisor implements CallAroundAdvisor, StreamAroundAdvisor {
    private static final Logger log = LoggerFactory.getLogger(MyLoggerAdvisor.class);

    @Override
    public AdvisedResponse aroundCall(AdvisedRequest advisedRequest, CallAroundAdvisorChain chain) {
        this.before(advisedRequest);
        AdvisedResponse advisedResponse = chain.nextAroundCall(advisedRequest);
        this.after(advisedResponse);
        return advisedResponse;
    }

    @Override
    public Flux<AdvisedResponse> aroundStream(AdvisedRequest advisedRequest, StreamAroundAdvisorChain chain) {
        this.before(advisedRequest);
        Flux<AdvisedResponse> advisedResponseFlux = chain.nextAroundStream(advisedRequest);
        //聚合
        return (new MessageAggregator()).aggregateAdvisedResponse(advisedResponseFlux, this::after);
    }

    @Override
    public String getName() {
        return this.getClass().getSimpleName();
    }

    @Override
    public int getOrder() {
        return 0;
    }

    //打印请求日志
    private void before(AdvisedRequest request) {
        log.info("AI request : {}", request.userText());
    }

    //打印响应日志
    private void after(AdvisedResponse response) {
        log.info("AI response : {}", response.response().getResult().getOutput().getText());
    }
}
